package org.compiere.apps.form;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;

import org.compiere.apps.form.z_invoiceList.invoice;
import org.compiere.model.MUser;
import org.compiere.model.Mzuser;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

/**
*
* @author alm
*/

public class SearchBPartner extends javax.swing.JFrame{

	zinvoice zinv;
	
	List<bp> list;
	
	private static CLogger	s_log	= CLogger.getCLogger (SearchBPartner.class);
    /**
     * Creates new form bpartner
     */
    public SearchBPartner(zinvoice zinv) {
    	
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(SearchBPartner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(SearchBPartner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(SearchBPartner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(SearchBPartner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
    	
        initComponents();
        this.zinv = zinv;
        // make the frame half the height and width
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (int) ((dimension.getWidth() - this.getWidth()) / 2);
        int y = (int) ((dimension.getHeight() - this.getHeight()) / 2);
        this.setLocation(x, y);        

        
    }

    class bp{
    	private int id;
    	private String iin;
    	private String name;
    	private String address;
		public String getIin() {
			return iin;
		}
		public void setIin(String iin) {
			this.iin = iin;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		
    }
    
    private void Google(String iin){
		
    	if(list != null)
    		list.clear();
    	
		String sql = "SELECT zuser_id, iin, name, adress FROM adempiere.zuser 	where iin like '%" + iin + "%'";
				
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try
		{
			pstmt = DB.prepareStatement (sql, null);
//			pstmt.setString(1, iin);
			rs = pstmt.executeQuery();
			list = new ArrayList<bp>();
			
			while (rs.next())
			{
//				 if(rs.getInt(1))
				 bp line = new bp();
				 line.setId(rs.getInt(1));
				 line.setIin(rs.getString(2));
				 line.setName(rs.getString(3));
				 line.setAddress(rs.getString(4));
				 list.add(line);
				 
			}
			if(list.size() > 0)
				jButton1.setEnabled(true);
			else
				jButton1.setEnabled(false);
			
			updateTable(list);
			
		}
		catch (SQLException e){
			s_log.log(Level.SEVERE, sql, e);
		}
		finally	{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
    }
    
    private void updateTable(List<bp> list){
    	DefaultTableModel model = new DefaultTableModel(
                new Object [][] {
                },
                new String [] {
    	                        "№",
    	                        "БИН",
    	                        "Наименование",
    	                        "Адрес"
                }
            );
    	
    	int i = 0;
    	for(bp line: list){
    			
    		 Object[] row = {i++, line.getIin(), line.getName(),line.getAddress()};
    		 model.addRow(row);
//    		 model.get
    	}
    	
    	jTable1.setModel(model);
        jTable1.setAutoResizeMode(jTable1.AUTO_RESIZE_OFF);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(70);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(150);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(150);    	
    }
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    	zinv.setBP(null);
    	dispose();
    }
    
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    	if(!jTextField1.getText().equals(""))
    		Google(jTextField1.getText());
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    	int row = jTable1.getSelectedRow();
    	if(row > -1){
    		Mzuser bp = new Mzuser(Env.getCtx(), list.get(row).getId(),null);
    		zinv.setBP(bp);
    		dispose();
    	}
    }    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

//        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Поиск бизнес парнера");
        setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(254, 254, 254));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/Search-Male-User-icon.png"))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabel2.setText("Поиск ");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(jLabel1)
                .addGap(28, 28, 28)
                .addComponent(jLabel2)
                .addContainerGap(319, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(24, 24, 24))))
        );

        jPanel1.setBounds(0, 0, 540, 70);
        jLayeredPane1.add(jPanel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPanel2.setBackground(new java.awt.Color(254, 254, 254));

//        jButton1.setBackground(java.awt.Color.blue);
        jButton1.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton1.setText("Выбрать");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton1ActionPerformed(evt);
            }
        });        

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton2.setText("Отмена");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(376, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        jPanel2.setBounds(0, 340, 540, 50);
        jLayeredPane1.add(jPanel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTextField1.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
//        jTextField1.setForeground(java.awt.SystemColor.activeCaptionBorder);
//        jTextField1.setText("ТОО Sanatec");
        jTextField1.setBounds(70, 120, 300, 23);
        jTextField1.addKeyListener(new KeyAdapter() {  
            public void keyTyped(KeyEvent e) {  
              char c = e.getKeyChar();  
              if (!(Character.isDigit(c) ||  
                 (c == KeyEvent.VK_BACK_SPACE) ||  
                 (c == KeyEvent.VK_DELETE))) {  
                   e.consume();  
                 }
            	if(!jTextField1.getText().equals("")){
                    if(c == KeyEvent.VK_ENTER)
                   	 jButton3ActionPerformed(null);
              	}
           	}
 
          });
        jLayeredPane1.add(jTextField1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jLabel3.setText("Введите БИН");
        jLabel3.setBounds(40, 100, 172, 13);
        jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("images/search-icon.png"))); // NOI18N
        jButton3.setPreferredSize(new java.awt.Dimension(50, 20));
        jButton3.setBounds(370, 120, 50, 23);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	jButton3ActionPerformed(evt);
            }
        });
        
        jLayeredPane1.add(jButton3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jTable1.setModel(
        		new DefaultTableModel(
                        new Object [][] {
                        },
                        new String [] {
            	                        "№",
            	                        "БИН",
            	                        "Наименование",
            	                        "Адрес"
                        }
                    ));
        
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(70);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(150);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(150);        
        jTable1.getTableHeader().setFont(new java.awt.Font("Tahoma", 0, 10));
        jTable1.setFont(new java.awt.Font("Tahoma", 0, 10));
        jScrollPane1.setViewportView(jTable1);

        jScrollPane1.setBounds(70, 150, 440, 160);
        jLayeredPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>


    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}
